import axios from 'axios'
import Cookies from 'js-cookie'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { addPending, removePending, cancelPending } from '@/utils/cancel-request'


import Vue from 'vue'

axios.defaults.withCredentials = true

// create an axios instance
const service = axios.create({
  baseURL: '/api', // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 100000 // request timeout
})
const serviceModel = axios.create({
  baseURL: '/workflow', // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 100000 // request timeout
})
const loadFile = axios.create({
  baseURL: '/', // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 100000 // request timeout
})
/**
 * @param {*} desc 错误提示
 * @param {*} type 错误类别
 * @param {*} time 显示时间
 */
function toast(desc, type = 'error', time = 3) {
  Message({
    dangerouslyUseHTMLString: true,
    message: desc,
    type: type,
    duration: time * 1000
  })
}
// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
      config.headers['X-CSRFToken'] = Cookies.get('csrftoken')
    }
    // 发送请求前首先检查该请求是否已经重复，重复则进行取消并移除
    cancelPending(config)
    // 添加该请求到pendingList中
    addPending(config)
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
serviceModel.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
      config.headers['X-CSRFToken'] = Cookies.get('csrftoken')
    }
    // 发送请求前首先检查该请求是否已经重复，重复则进行取消并移除
    cancelPending(config)
    // 添加该请求到pendingList中
    addPending(config)
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
loadFile.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['X-Token'] = getToken()
      config.headers['X-CSRFToken'] = Cookies.get('csrftoken')
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // 请求成功去除pengding状态
    removePending(response)
    return Promise.resolve(response)
  },
  error => {
    if (error && error.response) {
      // 请求失败去除pengding状态
      removePending(error.response)
      const result = error.response
      switch (result.status) {
        case 400:
          if(Array.isArray(result.data)) {
            result.data = result.data[0]
          }
          const errorList = Object.keys(result.data).map((key, index) => result.data[key][0])
          toast(errorList.join('</br>'))
          break
        case 403:
        // case 404:
          window.top.location.replace('/')
          break
        case 427:
          toast(result.data.detail)
          break
        case 500:
          toast('系统出现问题请求失败,请联系管理员')
          break
        default:
          toast('请求超时，请稍后再试')
          break
      }
    }
    return Promise.reject(error)
  }
)
serviceModel.interceptors.response.use(
  response => {
    // 请求成功去除pengding状态
    removePending(response)
    return Promise.resolve(response)
  },
  error => {
    if (error && error.response) {
      // 请求失败去除pengding状态
      removePending(error.response)
      const result = error.response.data
      switch (result.status) {
        case 400:
          toast(result.message)
          break
        case 403:
        case 404:
          window.history.go('/login')
          break
        case 427:
          toast(result.data.detail)
          break
        case 500:
          toast('系统出现问题请求失败,请联系管理员')
          break
        default:
          toast('请求超时，请稍后再试')
          break
      }
    }
    return Promise.reject(error)
  }
)
loadFile.interceptors.response.use(
  response => response,
  error => {
    console.log('err' + error) // for debug
    Message({
      message: '系统出现问题，请求失败',
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject('系统出现问题，请求失败')
  }
)

export { service, serviceModel, loadFile }
